<template>
  <a-drawer
    :width="340"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title> 条件 </template>
    <a-form-item
      class="item"
      field="tempName"
      label="配置优先级"
      validate-trigger="input"
      required
    >
      <a-space direction="vertical" size="large">
        <a-select placeholder="请选择">
          <a-option>优先级1</a-option>
          <a-option>优先级2</a-option>
        </a-select>
      </a-space>
    </a-form-item>
    <!-- 发起人条件 -->
    <a-form-item v-if="fqr" field="name" label="发起人">
      <a-input-tag
        v-model="userList"
        @click="gg()"
        @remove="removeTag($event)"
        placeholder="请选择发起人"
      />
    </a-form-item>
    <!-- 数量相关的条件 -->
    <template v-for="(item, index) in conditionConfig.item" :key="index">
      <a-form-item field="name" :label="item.showName">
        <a-space>
          <a-select
            v-model="item.optType"
            :options="selectTypeList"
            :field-names="fieldNames"
            placeholder="请选择"
          >
          </a-select>
          <a-input v-model="item.leftCustomContent" placeholder="请输入数值" />
        </a-space>
      </a-form-item>
    </template>
    <a-form-item class="item" field="tempName" validate-trigger="input">
      <a-space>
        <a-button type="primary" @click="addCondition()">添加条件</a-button>
      </a-space>
    </a-form-item>
    <a-modal
      v-model:visible="modalVisible"
      @ok="handleOkModal"
      @cancel="handleCancelModal"
    >
      <template #title> 添加条件 </template>
      <a-space direction="vertical" size="large">
        <a-checkbox v-model="fqr" @change="checkChange('fqr')">
          发起人
        </a-checkbox>
        <a-checkbox-group v-model="conditionIds" @change="checkChange($event)">
          <a-checkbox
            v-for="condition in conditionForm"
            :key="condition.id"
            :value="condition.name"
            >{{ condition.name }}</a-checkbox
          >
        </a-checkbox-group>
      </a-space>
    </a-modal>
    <a-modal
      v-model:visible="personModalVisible"
      @ok="personOk"
      @cancel="personCancel"
    >
      <template #title> 选择发起人 </template>
      <div>
        <div
          v-for="person in personList"
          :key="person.id"
          @click="addPerson(person)"
          >{{ person.name }}</div
        >
      </div>
    </a-modal>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { ref, computed, watch } from 'vue';
  import { useFlowStore } from '@/store';
  import { GetOrganizationchart } from '@/api/home/System settings/organizational-structure';
  import { isArray } from 'lodash';

  const selectTypeList = [
    { type: 1, text: '<' },
    { type: 2, text: '>' },
    { type: 3, text: '<=' },
    { type: 4, text: '=' },
    { type: 5, text: '>=' },
  ];
  const fieldNames = { value: 'type', label: 'text' };
  const props = withDefaults(
    //参数说明
    defineProps<{
      conditionForm: any;
    }>(),
    {}
  );
  const personModalVisible = ref(false);
  const personList = ref([]);
  const fqr = ref(false);
  const modalVisible = ref(false);
  const addCondition = () => {
    modalVisible.value = true;
  };
  const handleOkModal = () => {
    modalVisible.value = false;
  };
  const handleCancelModal = () => {
    modalVisible.value = false;
  };
  const store = useFlowStore();
  const closeDrawer = () => {
    store.setCondition(false);
  };
  let visible = computed({
    get() {
      return store.conditionDrawer;
    },
    set() {
      closeDrawer();
    },
  });

  const handleCancel = () => {
    store.setCondition(false);
  };
  let conditionConfig = ref({});
  let conditionsConfig = ref({
    conditionNodes: [],
  });
  let PriorityLevel = ref('');
  watch(
    () => store.conditionsConfig1,
    (val) => {
      conditionsConfig.value = val.value;
      PriorityLevel.value = val.priority;
      conditionConfig.value = val.priority
        ? conditionsConfig.value.conditionNodes[val.priority - 1]
        : { nodeUserList: [], conditionList: [] };
      fqr.value = conditionConfig.value.nodeUserList.length > 0 ? true : false;
      conditionConfig.value.item = conditionConfig.value.item?.length
        ? conditionConfig.value.item
        : [];
    }
  );
  const userList = computed(() => {
    let tags: any = [];
    if (conditionConfig.value.nodeUserList?.length > 0) {
      conditionConfig.value.nodeUserList.forEach((element: any) => {
        tags.push(element.userStaffName);
      });
    }
    return tags;
  });
  const conditionIds = computed(() => {
    let ids: any = [];
    //判断是否有其他条件，有则加入id
    conditionConfig.value.item?.forEach((item: any) => {
      ids.push(item.showName);
    });

    return ids;
  });
  // 选择条件，新增一个属性用来判断是否选择为条件设置
  const checkChange = (e: any) => {
    if (e === 'fqr') {
      if (!fqr.value) {
        conditionConfig.value.nodeUserList = [];
      }
    } else {
      let ids: any = [];
      conditionConfig.value.item.forEach((item: any) => {
        ids.push(item.showName);
      });
      e.forEach((item: any) => {
        if (item !== '' && !ids.includes(item)) {
          conditionConfig.value.item.push({
            type: 1,
            optType: 1,
            leftOptType: 0,
            rightOptType: 0,
            leftCustomContent: '',
            rightCustomContent: '',
            showName: item,
          });
        }
      });
      conditionConfig.value.item.forEach((item: any) => {
        if (!e.includes(item.showName)) {
          conditionConfig.value.item.splice(
            conditionConfig.value.item.findIndex(
              (condition: any) => condition.showName === item.showName
            ),
            1
          );
        }
      });
    }
  };
  const conditionForm = computed(() => {
    let obj: any = [];
    if (isArray(props.conditionForm)) {
      props.conditionForm.forEach((item: any) => {
        if (conditionIds.value.includes(item.name)) {
          item.isJoin = true;
        } else {
          item.isJoin = false;
        }
        obj.push(item);
      });
    }
    return obj;
  });

  const getPerson = async () => {
    let res = await GetOrganizationchart();
    personList.value = res.Staff;
  };
  const gg = () => {
    personModalVisible.value = true;
    getPerson();
  };
  // 删除指定成员
  const removeTag = (name: string) => {
    if (conditionConfig.value.nodeUserList?.length > 0) {
      conditionConfig.value.nodeUserList.splice(
        conditionConfig.value.nodeUserList.findIndex(
          (item) => item.userStaffName === name
        ),
        1
      );
    }
  };
  const addPerson = (person: any) => {
    let obj = {};
    obj.type = 1;
    obj.userStaffId = person.id;
    obj.userStaffName = person.name;
    conditionConfig.value.nodeUserList.push(obj);
  };
  const personCancel = () => {
    personModalVisible.value = false;
  };
  let emits = defineEmits(['update:nodeConfig']);
  const personOk = () => {
    personModalVisible.value = false;
  };
  const handleOk = () => {
    let a = conditionsConfig.value.conditionNodes.splice(
      PriorityLevel.value - 1,
      1
    ); //截取旧下标
    conditionsConfig.value.conditionNodes.splice(
      conditionConfig.value.priorityLevel - 1,
      0,
      a[0]
    ); //填充新下标
    conditionsConfig.value.conditionNodes.forEach((item, index) => {
      item.priorityLevel = index + 1;
    });
    store.setConditionsConfig({
      value: conditionsConfig.value,
      flag: true,
      id: store.conditionsConfig1.id,
    });
    store.setCondition(false);
  };
</script>

<style lang="less" scoped></style>
